import logging
import time
from django.utils import timezone

access_logger = logging.getLogger("django")


class AccessLogMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()

        response = self.get_response(request)

        duration = time.time() - start_time

        # 记录访问日志
        access_logger.info(
            f"{request.method} {request.path} {response.status_code} "
            f"{duration:.2f}s {self.get_client_ip(request)}"
        )

        return response

    def get_client_ip(self, request):
        x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
        if x_forwarded_for:
            return x_forwarded_for.split(",")[0]
        return request.META.get("REMOTE_ADDR")